package com.taotao.health.controller;

import java.util.Map;
import java.io.IOException;

import com.taotao.health.service.impl.ChatServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import com.taotao.common.core.web.controller.BaseController;

/**
 * 患者Controller
 *
 * @author zt
 * @date 2025-02-28
 */
@RestController
@RequestMapping("/health")
public class PatientController extends BaseController
{
    @Autowired
    private ChatServiceImpl chatService;

    @GetMapping("/send")
    public SseEmitter streamMessage(@RequestParam("message") String message) {
        if (message == null || message.isEmpty()) {
            throw new IllegalArgumentException("Message cannot be empty");
        }

        System.out.println("Received message: " + message);

        // 创建SSE连接，设置超时时间为30分钟
        SseEmitter emitter = new SseEmitter(30 * 60 * 1000L);

        // 设置完成回调
        emitter.onCompletion(() -> System.out.println("SSE completed"));
        emitter.onTimeout(() -> System.out.println("SSE timeout"));
        emitter.onError((ex) -> System.out.println("SSE error: " + ex.getMessage()));

        // 异步处理AI响应
        Thread thread = new Thread(() -> {
            try {
                // 发送开始提示
                System.out.println("Sending initial message");
                emitter.send(SseEmitter.event()
                    .data("正在思考...")
                    .build());

                chatService.streamChat(message, response -> {
                    try {
                        System.out.println("Sending chunk: " + response);
                        // 使用SseEmitter.event()构建事件
                        emitter.send(SseEmitter.event()
                            .data(response)
                            .build());
                    } catch (IOException e) {
                        System.out.println("Error sending chunk: " + e.getMessage());
                        emitter.completeWithError(e);
                    }
                });

                System.out.println("Chat completed, closing emitter");
                emitter.complete();
            } catch (Exception e) {
                System.out.println("Error in chat thread: " + e.getMessage());
                emitter.completeWithError(e);
            }
        });
        thread.start();

        return emitter;
    }

    // 保留原有的非流式接口以保持兼容性
    @PostMapping("/send/sync")
    public String sendMessage(@RequestBody Map<String, String> request) {
        String userInput = request.get("message");
        if (userInput == null || userInput.isEmpty()) {
            throw new IllegalArgumentException("Message cannot be empty");
        }
        return chatService.chat(userInput);
    }
}
